package org.opens.javaskill.audio;

import org.junit.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Mp3Download {

    /**
     * 功能:
     *      mp3文件下载器.
     * @throws Exception    读写异常
     */
    @Test
    public void test1() throws Exception {

        String mp3Url = "https://webfs.yun.kugou.com/201912062020/0fbdafc8247a2513ba7b69cea6ba7fb2/G139/M0A/1D/13/a5QEAFtXHOGAKTDZAC7nGkkF4wE028.mp3";
        //String mp3Url = "https://webfs.yun.kugou.com/201912062245/9d2ea075100250fffad684c920218f6a/G078/M08/18/17/jg0DAFgi6G-AKqsqADDP_nSW5F4051.mp3";
        //String mp3Url = "https://webfs.yun.kugou.com/201912062257/97e58b942604bee7dc45b41f14b00822/G131/M02/10/13/Y5QEAFtDBaCAWCvVADyU_3OVrSY440.mp3";

        URL url = new URL(mp3Url);

        File fileLocal = new File("F:\\music\\溯.mp3");

        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();

        urlCon.setConnectTimeout(6000);

        urlCon.setReadTimeout(6000);

        int code = urlCon.getResponseCode();

        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }

        //读文件流；
        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
        byte[] buffer = new byte[2048];
        int count = 0;

        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }

        out.close();
        in.close();
    }

}
